<?php

namespace app\index\controller;

use app\common\api\controller\Relation;
use app\common\model\Member;
use app\common\model\MemberFinance;
use think\Db;
use think\Request;
use think\wxpay\example\JsApiPay;
use app\common\controller\Wechat;
use think\wxpay\lib\WxPayUnifiedOrder;
use think\wxpay\lib\WxPayConfig;
use think\wxpay\lib\WxPayApi;
use app\common\api\controller\Bonus;
use think\Validate;

class Shop extends Home
{
    protected static $bonusRule = [];

    protected $beforeActionList = [
        'check_load' => ['except' => 'index,slides,getshopsbyfield,searchresult,goodsdetail,cates,check,search,notify,wechat,getarea,autologin,auth,flow,authnotify']
    ];

    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        self::$bonusRule = Db('BonusRule')->find();
    }

    /**
     * 获取轮播图
     */
    public function slides()
    {
        $slideList = Db('slide')->where(array('status' => 1))->limit(5)->select();
        if ($slideList) {
            foreach ($slideList as &$v) {
                $v['icon'] = get_cover($v['icon'], 'path');
            }
        }

        /*动态*/
        $documentInfo = Db('document')->where('status', 1)->order('id desc')->find();

        $this->apiSuccess('动态及轮播图', ['slideList' => $slideList, 'documentInfo' => $documentInfo]);
    }

    /**
     * 首页商品
     */
    public function index()
    {
        $map = [
            'status' => 1
        ];

        // 农场
        $list1 = Db('shop')->where($map)->where('is_farm', 1)->limit(3)->select();
        if ($list1) {
            foreach ($list1 as &$v1) {
                $v1['cover_ico'] = get_cover($v1['goods_ico'], 'path');
            }
        }

        // 严选
        $list2 = Db('shop')->where($map)->where('is_selecte', 1)->limit(3)->select();
        if ($list2) {
            foreach ($list2 as &$v2) {
                $v2['cover_ico'] = get_cover($v2['goods_ico'], 'path');
            }
        }

        $this->apiSuccess('首页农场和严选商品', ['lists1' => $list1, 'lists2' => $list2]);
    }

    /**
     * 根据字段获取商品列表
     */
    public function getShopsByField()
    {
        $page = input('page');
        if (!$page) {
            $page = 1;
        }
        $start = ($page - 1) * self::$totalList;
        $field = input('field');
        $field_arr = explode('_', $field);

        $map = ['status' => 1];
        if (isset($field_arr[1])) {
            $cateId = (int)$field_arr[1];
            $map['category_id'] = $cateId;
        } else {
            $field = 'is_' . $field_arr[0];
            $map[$field] = 1;
        }

        $order = 'id desc';
        $list = Db('shop')
            ->where($map)
            ->order($order . ',id desc')
            ->limit($start, self::$totalList)
            ->select();

        $totalCount = Db('shop')
            ->where($map)
            ->count();

        if ($totalCount > 0) {
            foreach ($list as &$v) {
                $v['cover_ico'] = get_cover($v['goods_ico'], 'path');
//                $v['product_name'] = $v['goods_name'];
//                $v['product_introduct'] = $v['goods_introduct'];
            }
        }

        $this->apiSuccess('商品列表', ['list' => $list, 'totalCount' => $totalCount]);
    }

    /**
     * 关键词搜索商品
     * @return mixed
     */
    public function searchResult()
    {
        $page = input('page');
        if (!$page) {
            $page = 1;
        }
        $start = ($page - 1) * self::$totalList;

        $keyword = input('keyword');
        if (!$keyword) {
            $this->error('请输入关键词！');
        }

        $list = Db('shop')
//            ->field('id,goods_name,goods_introduct,goods_ico,sell_num,member_price')
            ->where('status', 1)
            ->where('goods_name', 'like', '%' . $keyword . '%')
            ->limit($start, self::$totalList)
            ->order('id desc')
            ->select();

        $totalCount = Db('shop')
            ->where('status', 1)
            ->where('goods_name', 'like', '%' . $keyword . '%')
            ->count();

        if ($totalCount > 0) {
            foreach ($list as &$v) {
                $v['cover_ico'] = $v['goods_image'];
                $v['product_name'] = $v['goods_name'];
                $v['product_introduct'] = $v['goods_introduct'];
            }
        }

        $this->apiSuccess('搜索商品', ['list' => $list, 'totalCount' => $totalCount]);
    }

    /**
     * 显示商品详情页
     */
    function goodsdetail()
    {
        $goodid = input('id');
        if (is_numeric($goodid)) {
            $goodinfo = Db('shop')->find($goodid);
            $picsId = explode(',', $goodinfo['pics']);
            if (count($picsId) > 0) {
                $picsArr = [];
                foreach ($picsId as $v) {
                    $picsArr[] = get_cover($v, 'path');
                }
                $goodinfo['pics'] = $picsArr;
            }
            if ($goodinfo) {
                Db('shop')->where(array('id' => $goodid))->setInc('view');
            }

            if ($goodinfo['attr']) {
                $attrs = explode(',', $goodinfo['attr']);
                $arr = [];
                foreach ($attrs as $kk => $vv) {
                    $attrVal = explode(':', $vv);
                    $val = explode('|', $attrVal[1]);
                    $arr[$attrVal[0]] = $val;
                }
                $goodinfo['attr'] = $arr;
            }

            $this->apiSuccess('商品详情', $goodinfo);
        } else {
            $this->error('禁止非法操作！');
        }
    }

    /**
     * 商品分类
     */
    public function cates()
    {
        $map['status'] = 1;
        $map['pid'] = 0;
        $pcates = Db('shop_category')->where($map)->order('sort asc,id asc')->select();
        if ($pcates) {
            foreach ($pcates as &$val) {
                $val['icon'] = $_SERVER['SERVER_NAME'] . get_cover($val['icon'], 'path');
//                $idsArr = Db('shop_category')->where('status', 1)->where('pid', $val['id'])->column('id');
//                if (!$idsArr) {
//                    continue;
//                }
//                $shops = Db('shop')->where('category_id', 'in', $idsArr)->where('status', 1)->order('sort asc,createtime desc')->select();
//                if ($shops) {
//                    foreach ($shops as &$vv) {
//                        $vv['goods_ico'] = get_cover($vv['goods_ico'], 'path');
//                    }
//
//                }
//                $val['lists'] = $shops;
            }
        }

        $this->apiSuccess('商品分类', $pcates);
    }

    public function cart()
    {
        $uid = is_login();
        if (request()->isPost()) {
            $goodid = input('id');
            $shop = Db('shop')->where(array('id' => $goodid, 'status' => 1))->find();
            $gnum = input('num');

            $datanum = Db("shopcart")->where("goodid='$goodid'and uid='$uid'")->value("num");
            if ($datanum > 0) {
                $lastId = Db("shopcart")->where("goodid='$goodid'and uid='$uid'")->setInc('num', $gnum);
            } else {
                $price = $shop['member_price'];
//                $price2 = $shop['member_price'];

                $data['num'] = $gnum;
                $data['goodid'] = $goodid;
                $data['uid'] = $uid;
                $data['price'] = $price;
                $data['create_time'] = time();
                $lastId = Db("shopcart")->insert($data);
            }
            if ($lastId > 0) {
                $this->success('成功加入购物车！', url('cart'));
            } else {
                $this->error('加入购物车失败！');
            }
        } else {
            $cartlist = Db('shopcart')->where(array('uid' => is_login()))->select();
            $sum_nums = 0;
            $sum_goods = 0;
            foreach ($cartlist as $k => $val) {
                $shop = Db("shop")->where(array('id' => $val['goodid'], 'status' => 1))->find();
                $cartlist[$k]['goods_ico'] = $shop['goods_ico'];
                $cartlist[$k]['goods_name'] = $shop['goods_name'];
                $cartlist[$k]['goods_introduct'] = $shop['goods_introduct'];
                $cartlist[$k]['category_id'] = $shop['category_id'];
                $sum_nums += $val['num'];
                $sum_goods += $val['num'] * $val['price'];
            }
            $selfinfo = Db('member')->where(array('uid' => $uid))->find();
            $this->assign('hasmoney', $selfinfo['hasmoney']);

            $this->assign('sum_nums', $sum_nums);
            $this->assign('sum_goods', $sum_goods);
            $this->assign('cartlist', $cartlist);
            $this->assign('title', "我的购物车");
            return $this->fetch();
        }
    }

    /**
     * 删除购物车中某个商品
     * @return [type] [description]
     */
    public function delItemByid()
    {
        if (request()->isPost()) {
            $id = input('id');
            $uid = is_login();
            $result = Db('shopcart')->where('id', $id)->where('uid', $uid)->delete();
            if ($result) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
        }
    }

    /**
     * 地址管理
     */
    public function address()
    {
        $uid = is_login();
        if (request()->isPost()) {
            $data = $_POST;
            $rule = [
                'province|省' => 'require',
                'city|市' => 'require',
                'district|县' => 'require',
                'address|详细地址' => 'require',
                'realname|姓名' => 'require',
                'mobile|手机号码' => 'require'
            ];
            $validate = new Validate($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            };
            $data['area'] = $data['province'] . ',' . $data['city'] . ',' . $data['district'];
            unset($data['province'], $data['city'], $data['district']);
            if (!empty($data)) {
                $data['create_time'] = time();
                $data['uid'] = $uid;
                if (isset($data['status'])) {
                    $data['status'] = 1;
                    Db('transport')->where('uid', $uid)->setField('status', 0);
                } else {
                    $data['status'] = 0;
                }
                $result = Db('transport')->insert($data);
                if ($result) {
                    $this->success('地址添加成功');
                } else {
                    $this->error('地址添加失败');
                }
            }
        } else {
            $list = Db("transport")->where('uid', $uid)->select();
            foreach ($list as &$v) {
                $area = $this->getAddress($v['area']);
                $v['address'] = $area . $v['address'];
            }
            $this->assign('_list', $list);
            $this->assign('title', '地址管理');
            return $this->fetch();
        }
    }

    /**
     * 获取所有收货地址
     */
    public function getAllAddress()
    {
        $uid = $this->uid;
        $addresses = Db("transport")->where('uid', $uid)->order('id desc')->select();
        if ($addresses) {
            foreach ($addresses as &$v) {
                $areaId = $v['area'];
                $v['area_arr'] = $this->getAreaAddressThree($areaId);
                $v['area'] = implode("", $this->getAreaAddressThree($areaId));
                $v['area_id'] = $areaId;
            }
        }

        $this->apiSuccess('所有收货地址', $addresses);
    }

    /**
     * 添加或编辑地址
     */
    public function editAddress()
    {
        $input = input();
        $uid = $this->uid;
        if (isset($input['default']) && $input['default'] == "true") {
            Db("transport")->where('uid', $uid)->update(['status' => 0]);
            $input['status'] = 1;
        } else {
            $input['status'] = 0;
        }

        if (isset($input['id']) && $input['id'] > 0) {
            $id = $input['id'];
        } else {
            $id = 0;
        }

        $data = [
            'uid' => $uid,
            'realname' => $input['realname'],
            'mobile' => $input['mobile'],
            'area' => $input['area'],
            'address' => $input['address'],
            'status' => $input['status']
        ];

        if ($id <= 0) {
            $data['create_time'] = time();
            $res = Db("transport")->insert($data);
            $msg = '添加';
        } else {
            $res = Db("transport")->where('id', $id)->update($data);
            $msg = '更新';
        }

        if ($res) {
            $this->apiSuccess($msg . '成功！');
        } else {
            $this->apiError($msg . '失败！');
        }
    }

    /**
     * 新增收货地址
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addAddress()
    {
        $uid = is_login();
        if (request()->isPost()) {
            $data = $_POST;
            $rule = [
                'realname|姓名' => 'require',
                'mobile|联系方式' => 'require|length:11|number',
                'province|省' => 'require',
                'city|市' => 'require',
                'district|县' => 'require',
                'address|详细地址' => 'require'
            ];
            $validate = new Validate($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            };

            Db('transport')->where('uid', $uid)->setField('status', 0);
            $province = $data['province'];
            $city = $data['city'];
            $district = $data['district'];
            $area = $province . ',' . $city . ',' . $district;
            $data['area'] = $area;
            $data['uid'] = $uid;
            $data['status'] = 1;
            unset($data['province'], $data['city'], $data['district']);
            $res = Db('transport')->insert($data);
            if ($res) {
                $this->success('修改成功！', url('address'));
            } else {
                $this->error('修改失败！');
            }
        } else {
            $this->assign('title', '添加收货地址');
            return $this->fetch('addaddress');
        }
    }

    /**
     * 设置某个地址为默认地址
     * @return [type] [description]
     */
    public function shezhi()
    {
        $id = input('id');
        $uid = is_login();
        Db('transport')->where("uid='$uid'")->setField('status', 0);

        $result = Db('transport')->where("uid='$uid' and id='$id'")->setField("status", 1);
        if ($result) {
            $this->success('设置成功');
        } else {
            $this->error('设置失败');
        }
    }

    /**
     * 删除一个收货地址
     * @return [type] [description]
     */
    public function deleteAddress()
    {
        if (request()->isPost()) {
            $uid = is_login();
            $id = input('post.id');
            if (Db('transport')->where("uid='$uid' and id='$id'")->delete()) {
                $this->success("删除成功");
            } else {
                $this->error("删除失败");
            }
        }
    }

    /**
     * 默认收货地址
     * @return mixed
     */
    public function getDefaultAddress()
    {
        $uid = $this->uid;
        $default = Db('transport')->where('uid', $uid)->where('status', 1)->find();

        if ($default) {
            $default['area_arr'] = $this->getAreaAddressThree($default['area']);
            $default['area'] = implode("", $this->getAreaAddressThree($default['area']));
            $default['address'] = $default['area'] . $default['address'];
        }

        $this->apiSuccess('默认收货地址！', $default);
    }

    /**
     * 商品结算
     */
    public function order()
    {
        $data = input('data');
        if (!$data) {
            $this->apiError('参数缺失！');
        }

        $dataArr = json_decode($data, true);
        if (count($dataArr) <= 0) {
            $this->apiError('请至少选择一个商品！');
        }

        $uid = $this->uid;
        $user = Member::find($uid);

        $numArr = array_column($dataArr, 'number');
        $totalNum = array_sum($numArr);
        $type = input('type', 1);

        if ($user->userrank <= 0) {
            if ($type == 3) {
                $this->apiError('不可购买复消区产品！');
            }
            $bill_condition_arr = 'bill_condition' . $type;
            $billConditionStr = get_bonus_rule($bill_condition_arr);
        } elseif ($user->userrank == 1) {
            if ($type == 1) {
                $this->apiError('不可购买初级区产品！');
            }
            if ($type == 2) {
                $bill_condition_arr = 'bill_condition' . $type;
                $billConditionStr = get_bonus_rule($bill_condition_arr);
            } else {
                $billConditionStr = get_bonus_rule('cp_condition');
            }
        } else {
            if (in_array($type, [1, 2])) {
                $this->apiError('只能购买复消区产品！');
            }
            $billConditionStr = get_bonus_rule('cp_condition');
        }

        $billConditionArr = user_level_bonus_format($billConditionStr);
        $first = reset($billConditionArr);

        if ($totalNum != $first[3]) {
            $this->apiError('数量无法达到标准，请重新选择！');
        }

        $markArr = [];
        foreach ($dataArr as $v) {
            $sInfo = Db('shop')->where('id', $v['id'])->find();
            $mark = Db('shop_category')->where('id', $sInfo['category_id'])->value('mark');

//            if ($user['userrank'] == 0) {
//                if ($mark != 'bill') {
//                    $this->apiError('必须先购买报单产品！');
//                }
//            } else {
//                if ($mark == 'bill') {
//                    $this->apiError('不可购买报单产品！');
//                }
//            }

            if (!in_array($mark, $markArr)) {
                array_push($markArr, $mark);
            }
        }

        if (count($markArr) >= 2) {
            $this->apiError('一次只能购买一个种类的商品！');
        }

        $tag = create_order($uid);

        $list = [];
        foreach ($dataArr as $k => $v) {
//            if ($v['parameter_id' <= 0) {
//                $this->apiError('商品规格缺失！');
//            }
            $sInfo = Db('shop')->where('id', $v['id'])->find();

            if ($sInfo['goods_num'] < $v['number']) {
                $this->apiError('商品余量不足！');
            }

            $price = $sInfo['member_price'];
//            if ($user->userrank >= 1) {
//                $discountRate = get_bonus_rule('discount_rate');
//                $price = ($sInfo['stock'] * $discountRate * 0.01) + $sInfo['money'];
//            }

            $item = [
                'goodid' => $v['id'],
                'goodname' => $sInfo['goods_name'],
                'num' => $v['number'],
                'uid' => $uid,
                'tag' => $tag,
                'create_time' => time(),
//                'parameters' => $parameters_arr[$k],
                'price' => $price,
                'total' => $price * $v['number']
            ];
            array_push($list, $item);
        }

        $res = Db('shoplist')->insertAll($list);
        if ($res) {
            $this->apiSuccess('生成商品清单！', $tag);
        } else {
            $this->apiError('操作失败！');
        }
    }

    /**
     * 获取商品清单
     */
    public function getOrder()
    {
        $tag = input('tag');
        $lists = Db('shoplist')->where("tag", $tag)->order('id desc')->select();

        $money = $stock = $total = $num = $transfee = 0;

        foreach ($lists as &$val) {
            $pInfo = Db('shop')->where('id', $val['goodid'])->find();
//            $val['goodname'] = $pInfo['goodname'];
            $val['cover_ico'] = get_cover($pInfo['goods_ico'], 'path');
            $val['goods_introduct'] = $pInfo['goods_introduct'];

            $total += $val['total'];
            $num += $val['num'];        //商品数量
            $transfee += $pInfo['transfee'] * $val['num'];

            $val['money'] = $pInfo['money'];
            $val['stock'] = $pInfo['stock'];

//            $money += round($pInfo['money'] * $num, 2);
//            $stock += round($pInfo['stock'] * $num, 2);

//            $parameter = ProductSku::where('id', $val->parameter_id)->value('value');
//            $val->parameter = $parameter;
        }

        $uid = $this->uid;
        $user = Member::find($uid);

        $moneyArr = $this->getShopsData($user->userrank, $num);

        $data = [
            'list' => $lists,
            'transfee' => $transfee,
            'num' => $num,
            'money' => round($moneyArr['money'], 2),
            'stock' => round($moneyArr['stock'], 2),
            'total' => round($moneyArr['money'] + $moneyArr['stock'], 2),
        ];

        $this->apiSuccess('商品清单！', $data);
    }

    /**
     * 生成一个随机订单号
     * @return [type] [description]
     */
    function ordersn()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2015] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%04d%02d', rand(1000, 9999), rand(0, 99));
        return $orderSn;
    }

    /**
     * 获取商品下单数据
     * @param $userrank
     * @param $num
     * @return array
     */
    private function getShopsData($userrank, $num)
    {
        if ($userrank <= 0) {
            $billConditionStr1 = get_bonus_rule('bill_condition1');
            $billConditionStr2 = get_bonus_rule('bill_condition2');
            $billConditionArr1 = reset(user_level_bonus_format($billConditionStr1));
            $billConditionArr2 = reset(user_level_bonus_format($billConditionStr2));
            if (!in_array($num, [$billConditionArr1[3], $billConditionArr2[3]])) {
                $this->apiError('数量无法达到标准，请重新选择！');
            }

            if ($num == $billConditionArr1[3]) {
                $money = $billConditionArr1[1];
                $stock = $billConditionArr1[2];
            } else {
                $money = $billConditionArr2[1];
                $stock = $billConditionArr2[2];
            }

        } elseif ($userrank == 1) {
            $billConditionStr2 = get_bonus_rule('bill_condition2');
            $billConditionArr2 = reset(user_level_bonus_format($billConditionStr2));
            $billConditionStr = get_bonus_rule('cp_condition');
            $billConditionArr = reset(user_level_bonus_format($billConditionStr));

            if (!in_array($num, [$billConditionArr2[3], $billConditionArr[3]])) {
                $this->apiError('数量无法达到标准，请重新选择！');
            }

            if ($num == $billConditionArr2[3]) {
                $money = $billConditionArr2[1];
                $stock = $billConditionArr2[2];
            } else {
                $money = $billConditionArr[1];
                $stock = $billConditionArr[2];
            }

        } else {
            $billConditionStr = get_bonus_rule('cp_condition');
            $billConditionArr = reset(user_level_bonus_format($billConditionStr));

            if ($num != $billConditionArr[3]) {
                $this->apiError('数量无法达到标准，请重新选择！');
            }

            $money = $billConditionArr[1];
            $stock = $billConditionArr[2];
        }

        return ['money' => $money, 'stock' => $stock, 'number' => $num];
    }

    /**
     * 提交订单
     */
    public function createorder()
    {
        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }
        $uid = $this->uid;
        $tag = input('tag'); //标识号
//            $payType = input('paytype');
//            if (!in_array($payType, [1, 2, 3])) {
//                $this->error('非法操作！');
//            }

        $uinfo = Db('member')->where(array('uid' => $uid))->find();
        $password = input('password');
        if ($uinfo['psd2'] != $password) {
            $this->apiError('支付密码错误！');
        }

        $shop_order = Db('shop_order')->where('orderid', $tag)->find();
        if ($shop_order) {
            $this->apiError('重复提交订单');
        }

        $addressid = Db('transport')->where("status='1' and uid='$uid'")->value('id');
        if ($addressid <= 0) {
            $this->apiError('必须选择一个收货地址！');
        }

        //获取该用户购物清单中的数据
        $shoplist = Db('shoplist')->where('tag', $tag)->select();

        if (!$shoplist) {
            $this->apiError('请先购买商品！');
        }

        $nums = 0;
        $total = 0;
        $transfee = 0;
        $needMoney = 0;
        $needStock = 0;
        $markArr = [];
        foreach ($shoplist as $v) {
            $shop = Db('shop')->where('id', $v['goodid'])->find();
            $cateInfo = Db('shop_category')->where('id', $shop['category_id'])->find();

            if ($uinfo['userrank'] == 0) {
                if ($cateInfo['mark'] != 'bill') {
                    $this->apiError('必须先购买报单产品！');
                }
            } elseif ($uinfo['userrank'] == 2) {
                if ($cateInfo['mark'] == 'bill') {
                    $this->apiError('不可购买报单产品！');
                }
            }

            if (!in_array($cateInfo['mark'], $markArr)) {
                array_unshift($markArr, $cateInfo['mark']);
            }

            $nums += $v['num'];
//            $needMoney += round($shop['money'] * $v['num'], 2);
//            $needStock += round($shop['stock'] * $v['num'], 2);
//            $total += $v['total'];
            $transfee += $shop['transfee'] * $v['num'];
        }

        $shopsData = $this->getShopsData($uinfo['userrank'], $nums);
        $needMoney = $shopsData['money'];
        $needStock = $shopsData['stock'];
        $total = $needMoney + $needStock;

        $markArr = array_unique($markArr);

        if (count($markArr) >= 2) {
            $this->apiError('一次只能购买一个种类的商品！');
        }

        $mark = $markArr[0];
//        if ($mark == 'cp') {
//            $discountRate = get_bonus_rule('discount_rate');
//            $needStock = round($needStock * $discountRate * 0.01, 2);
//        }

        $all = $total + $transfee;
        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();

        if ($mark == 'bill') {
            // 报单
            if ($needStock > $memberFinanceModel->hasbill) {
                $this->apiError('账户报单积分余额不足，无法购买！');
            }

        } else {
            // 复消
            if ($needStock > $memberFinanceModel->hascp) {
                $this->apiError('账户复消积分余额不足，无法购买！');
            }
        }

        if ($needMoney > $memberFinanceModel->hasmoney) {
            $this->apiError('账户现金币余额不足，无法购买！');
        }

        $message = input('message');
        $data['addressid'] = $addressid;//收货人地址
        $data['total'] = $total;//总金额
        $data['transfee'] = $transfee;
        $data['all'] = $total + $transfee;
        $data['orderid'] = $tag;//订单号
        $data['uid'] = $uid;//当前用户id
        $data['backinfo'] = '已下单';
        $data['message'] = $message;
        $data['paytype'] = 1;//等待发货
        $data['mark'] = $mark;
        $data['status'] = 0;
        $data['create_time'] = time();

        //根据订单id保存对应的费用数据
        Db('shop_order')->insert($data);
        $order_id = Db('shop_order')->getLastInsID();
        $res = Db('shoplist')->where('tag', $tag)->setField('orderid', $order_id);

        unset($data);
        if ($res) {

            Db::startTrans();
            try {

                if ($mark == 'bill') {
                    // 报单
                    $memberFinanceModel->hasbill -= $needStock;
                } else {
                    // 复消
                    $memberFinanceModel->hascp -= $needStock;
                }

                $memberFinanceModel->hasmoney -= $needMoney;
                $memberFinanceModel->save();

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }

            if ($mark == 'bill') {
                $type = array('recordtype' => 0, 'changetype' => 26, 'moneytype' => 1);
                $money = array('money' => $needStock, 'hasmoney' => $memberFinanceModel->hasbill);
                money_change($type, $uid, 0, $money, $tag);
                unset($type, $money);
            } else {
                $type = array('recordtype' => 0, 'changetype' => 26, 'moneytype' => 3);
                $money = array('money' => $needStock, 'hasmoney' => $memberFinanceModel->hascp);
                money_change($type, $uid, 0, $money, $tag);
                unset($type, $money);
            }

            $type = array('recordtype' => 0, 'changetype' => 26, 'moneytype' => 2);
            $money = array('money' => $needMoney, 'hasmoney' => $memberFinanceModel->hasmoney);
            money_change($type, $uid, 0, $money, $tag);
            unset($type, $money);

            if ($uinfo['userrank'] == 0) {
                (new Relation())->getPosition($uid);
            }

            $bonus = new Bonus($uid, $needStock, $mark);
            if ($uinfo['userrank'] <= 0) {
                // 先发奖后升级
                $bonus->bonusRecom();
                $bonus->bonusPoint1();
                $bonus->bonusStore();
                $bonus->bonusUpdate();
            } elseif ($uinfo['userrank'] == 1) {
                // 先发奖后升级
                if ($mark == 'bill') {
                    $bonus->bonusRecom();
                    $bonus->bonusPoint1();
                    $bonus->bonusStore();
                    $bonus->bonusUpdate();
                } elseif ($mark == 'cp') {
                    $bonus->bonusPoint2();
                }
            } else {
                $bonus->bonusPoint2();
            }

            $bonus->addAchievement();
            /*更新状态*/
            $ndata = [
                'pay_time' => time(),
                'status' => 1
            ];
            Db('shop_order')->where('id', $order_id)->update($ndata);
            Db('shoplist')->where('orderid', $order_id)->update($ndata);

            finance1($needStock);

            /*公司发货更新商品销量*/
            $shoplists = Db('shoplist')->where('tag', $tag)->select();
            self::updateShop($shoplists);

            $this->apiSuccess("订单提交成功！");
        } else {
            $this->apiError("订单提交失败！", url('index'));
        }
    }

    /**
     * 微信支付
     */
    public
    function wechat()
    {
        $uid = is_login();
        $user = Db('member')->where('uid', $uid)->find();
        $orderid = input('orderid');
        $res = Db('shop_order')->where(array("orderid" => $orderid))->find();
        if ($res) {
            $ass = 'res' . $uid;
            session($ass, $res);
        }

//        //①、获取用户openid
        $tools = new JsApiPay();
        $openId = $tools->GetOpenid();
//        p($openId);
        //②、统一下单
        $ass = 'res' . $uid;
        $res = session($ass);

        $total = $res['all'] * 100;

        //地址
        $addressid = $res['addressid'];
        $address = Db('transport')->where(array("id" => $addressid))->find();
        $address['area'] = $this->getAddress($address['area']);
        $this->assign('address', $address);
        $input = new WxPayUnifiedOrder();
        $input->SetBody("购物");
        $input->SetAttach(1);
        $input->SetOut_trade_no($res['orderid']);

        $input->SetTotal_fee($total);
        //$input->SetTime_start(date("YmdHis"));
        //$input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://nmb.lhtxsm.com/index/Shop/notify");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign('jsApiParameters', $jsApiParameters);
        $this->assign('res', $res);
        return $this->fetch();
    }

    /**
     * @return string
     * 微信回调
     */
//    public function notify()
//    {
//        //获取返回的xml数据
////        $notify = $GLOBALS['HTTP_RAW_POST_DATA'];
//        $notify = file_get_contents("php://input");
//
//        //奖xml数据转换成数组
//        $replay = json_decode(json_encode(simplexml_load_string($notify, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
//
//        //file_put_contents("log111.txt",$notify,FILE_APPEND);
//
//        //保存原sign
//        $replay_sign = $replay['sign'];
//        unset($replay['sign']);
//        ksort($replay);
//        foreach ($replay as $k => $v) {
//            if ($k != "sign" && $v != "" && !is_array($v)) {
//                $buff .= $k . "=" . $v . "&";
//            }
//        }
//        $string = trim($buff, "&");
//        //签名步骤二：在string后加入KEY
//        $string = $string . "&key=" . WxPayConfig::KEY;
//        //签名步骤三：MD5加密
//        $string = md5($string);
//        //签名步骤四：所有字符转为大写
//        $sign = strtoupper($string);
////        Db('bonus_rule')->where('id', 1)->setField('title', $sign);
//        //file_put_contents("log0.txt",$sign."\n",FILE_APPEND);
//        if ($sign == $replay_sign && $replay['return_code'] == 'SUCCESS' && $replay['result_code'] == 'SUCCESS') {
//            //执行逻辑
//            $tag = $replay['out_trade_no'];
////            Db('bonus_rule')->where('id', 1)->setField('title', $tag);
//            $orderInfo = DB("ShopOrder")->where(array('orderid' => $tag))->find();
//            $order_id = $orderInfo['id'];
//            $fmark = $orderInfo['mark'];
//            $uid = $orderInfo['uid'];
//            $total = $orderInfo['total'];
//
//            $shoplist = Db('shoplist')->where('orderid', $order_id)->find();
//            $shop = Db('shop')->where('id', $shoplist['goodid'])->find();
//            $secondCate = Db('shop_category')->where('id', $shop['category_id'])->find();
//            preg_match("/\d+/is", $secondCate['mark'], $match);
//            $smark = $match[0];
//
//            /*更新状态*/
//            Db('shop_order')->where('id', $order_id)->setField('status', 1);
//            Db('shoplist')->where('orderid', $order_id)->setField('status', 1);
//
//            if ($fmark == 'bill') {
//                $bonus = new Bonus();
//                $bonus->bonus1($uid, $total);/*分享奖*/
//                $area = Db('transport')->where('id', $orderInfo['addressid'])->value('area');
//                $bonus->bonus2($uid, $total, $area);/*领导奖*/
//
//                /*赠送折扣券*/
//                $cdata = [
//                    'uid' => $uid,
//                    'orderid' => $order_id,
//                    'type' => $smark,
//                    'touse' => 0,
//                    'create_time' => time(),
//                    'status' => 1
//                ];
//
//                Db('coupons')->insert($cdata);
//                Db('coupons')->insert($cdata);
//
//                /*出局*/
//                $number = Db('shop_order')->where('mark', 'bill')->count();
//                if (($number - 1) % 2 == 0) {
//                    $bonus = new Bonus();
//                    $bonus->bonus3($uid);
//                }
//            } elseif ($fmark == 'discount') {
//                Db('coupons')->where('type', $smark)->where('uid', $uid)->where('status', 1)->update(['status' => -1, 'touse' => $use]);
//
//                $pdeep = Db('bmember')->max('pdeep');
//                $orderid = Db('shop_order')->where('uid', $uid)->where('mark', 'bill')->max('id');
//                $mdata = [
//                    'uid' => $uid,
//                    'orderid' => $orderid,
//                    'create_time' => time(),
//                    'update_time' => time(),
//                    'type' => $smark,
//                    'pdeep' => $pdeep + 1,
//                    'status' => 1
//                ];
//
//                Db('bmember')->insert($mdata);
//            }
//
//            /*公司发货更新商品销量*/
//            $shoplists = Db('shoplist')->where('tag', $tag)->select();
//            self::updateShop($shoplists);
//            $result = true;
//        } else {
//            $result = false;
//        }
//        if ($result) {
//            //file_put_contents("log1111.txt",$result,FILE_APPEND);
//
//            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
//        } else {
//            //file_put_contents('./text', 'error');
//            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
//        }
//
//        echo $str;
//        return $str;
//    }

    public
    function auth()
    {
        $uid = is_login();
        $user = Db('member')->where('uid', $uid)->find();
        if ($user['status'] == 1) {
            $this->error('你已认证！');
        }
//        //①、获取用户openid
        $tools = new JsApiPay();
        $openId = $tools->GetOpenid1();
//        p($openId);
        //②、统一下单
        $total = 100;
        $orderid = create_order($uid);
        Db('member')->where('uid', $uid)->setField('orderid', $orderid);
        $input = new WxPayUnifiedOrder();
        $input->SetBody("认证");
        $input->SetAttach(1);
        $input->SetOut_trade_no($orderid);

        $input->SetTotal_fee($total);
        //$input->SetTime_start(date("YmdHis"));
        //$input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://nmb.lhtxsm.com/index/Shop/authNotify");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign('jsApiParameters', $jsApiParameters);
        return $this->fetch();
    }

    public
    function authNotify()
    {
        //获取返回的xml数据
//        $notify = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify = file_get_contents("php://input");

        //奖xml数据转换成数组
        $replay = json_decode(json_encode(simplexml_load_string($notify, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //file_put_contents("log111.txt",$notify,FILE_APPEND);

        //保存原sign
        $replay_sign = $replay['sign'];
        unset($replay['sign']);
        ksort($replay);
        foreach ($replay as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $string = trim($buff, "&");
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . WxPayConfig::KEY;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $sign = strtoupper($string);
//        Db('bonus_rule')->where('id', 1)->setField('title', $sign);
        //file_put_contents("log0.txt",$sign."\n",FILE_APPEND);
        if ($sign == $replay_sign && $replay['return_code'] == 'SUCCESS' && $replay['result_code'] == 'SUCCESS') {
            //执行逻辑
            $orderid = $replay['out_trade_no'];
            $uid = Db('member')->where('orderid', $orderid)->value('uid');
            $data = [
                'status' => 1,
                'active_time' => time()
            ];
            Db('member')->where('uid', $uid)->update($data);
            Db('ucenter_member')->where('id', $uid)->setField('status', 1);
            $result = true;
        } else {
            $result = false;
        }
        if ($result) {
            //file_put_contents("log1111.txt",$result,FILE_APPEND);

            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            //file_put_contents('./text', 'error');
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }

        echo $str;
        return $str;
    }

    /**
     * 更新商品销量
     * @param $list
     * @throws \think\Exception
     */
    private
    function updateShop($list)
    {
        $shop = Db('Shop');
        foreach ($list as $k => $val) {
            $goodid = $val["goodid"];
            $shop->where(array('id' => $goodid))->setInc('sell_num', $val['num']);
            $shop->where(array('id' => $goodid))->setDec('goods_num', $val['num']);
            unset($goodid);
        }
    }

    public
    function search()
    {
        /*类别id*/
        $categoryid = input('cateid', '');
        $this->assign('cateid', $categoryid);
        /*关键词*/
        $keyword = input('keyword', '');
        $this->assign('keyword', $keyword);
        /*排序*/
        $sort = input('sort', 'changetime');
        $this->assign('sort', $sort);
        $order = $sort . ' desc';
        if ($sort == 'member_price') {
            $order = $sort . ' asc';
        }
        //根据id查询此种类下的前8条数据
        if ($categoryid) {
            $map['category_id'] = $categoryid;

        }

        $map['status'] = 1;
        if ($keyword) {
            $map ['goods_name|goods_introduct|goods_detail'] = array('like', '%' . $keyword . '%');

        }
        $categoryList = Db('shop')->where($map)->order($order)->select();
        $this->assign('categoryLists', $categoryList);

        $this->assign('title', '分类页商品');
        return $this->fetch();
    }

    /**
     * 是否收藏商品
     */
    public function isCollect()
    {
        $id = input('id');
        $info = Db('shop')->where('status', 1)->find($id);
        if (!$info) {
            $this->apiError('该商品不存在');
        }

        $uid = $this->uid;
        $collInfo = Db('collection_product')->where('uid', $uid)->where('product_id', $id)->find();
        if (!$collInfo) {
            $this->apiSuccess('尚未收藏', ['status' => 1, 'data' => false]);
        } else {
            $this->apiSuccess('已收藏', ['status' => 1, 'data' => true]);
        }
    }

    /**
     * 更新商品收藏
     */
    public function changeCollect()
    {
        $id = input('id');
        $info = Db('shop')->where('status', 1)->find($id);
        if (!$info) {
            $this->apiError('该商品不存在');
        }

        $uid = $this->uid;
        $collInfo = Db('collection_product')->where('uid', $uid)->where('product_id', $id)->find();
        if (!$collInfo) {
            $data = [
                'uid' => $uid,
                'product_id' => $id,
                'create_time' => time(),
                'update_time' => time()
            ];
            $res = Db('collection_product')->insert($data);
            if ($res) {
                $this->apiSuccess('收藏成功！');
            } else {
                $this->apiError('收藏失败！');
            }
        } else {
            $res = Db('collection_product')->delete($collInfo['id']);
            if ($res) {
                $this->apiSuccess('取消收藏成功！');
            } else {
                $this->apiError('取消收藏失败！');
            }
        }
    }

    /**
     * 商品收藏列表
     */
    public function shopCollect()
    {
        $page = input('page');
        $start = ($page - 1) * self::$totalList;

        $uid = $this->uid;
        $collInfos = Db::table('zx_collection_product')->join('zx_shop shop', 'zx_collection_product.product_id = shop.id')
            ->field('zx_collection_product.id,zx_collection_product.product_id,shop.goods_name,shop.goods_introduct,shop.goods_ico,shop.member_price')
            ->where('zx_collection_product.uid', $uid)
            ->where('shop.status', 1)
            ->order('zx_collection_product.id desc')
            ->limit($start, self::$totalList)
            ->select();

        $totalCount = Db::table('zx_collection_product')->join('zx_shop shop', 'zx_collection_product.product_id = shop.id')
            ->where('zx_collection_product.uid', $uid)
            ->where('shop.status', 1)
            ->count();

        if ($collInfos) {
            foreach ($collInfos as &$v) {
                $v['goods_ico'] = get_cover($v['goods_ico'], 'path');

//                $sku = ProductSku::where('product_id', $v->product_id)->where('number', '>=', 1)->orderBy('member_price', 'asc')->first();
//                if ($sku) {
//                    $member_price = $sku->member_price;
//                    $parameter = $sku->value;
//                    $parameterId = $sku->id;
//                } else {
//                    $member_price = 0.00;
//                    $parameter = '无';
//                    $parameterId = 0;
//                }

//                $v->price = $member_price;
//                $v->parameter = $parameter;
//                $v->parameter_id = $parameterId;
            }
        }

        $this->apiSuccess('商品收藏列表', ['data' => $collInfos, 'totalCount' => $totalCount]);
    }

    /**
     * 删除收藏
     */
    public function delCollect()
    {
        $uid = $this->userinfo['uid'];
        $ids = input('ids');

        $idsArr = array_unique(explode(',', $ids));

        $res = Db('collection_product')->where('uid', $uid)->where('id', 'in', $idsArr)->delete();
        if ($res) {
            $this->apiSuccess('删除成功');
        } else {
            $this->apiError('删除失败');
        }

    }

    /**
     * 商品浏览记录
     */
    public function shopBrowser()
    {
        $page = input('page');
        $start = ($page - 1) * self::$totalList;

        $uid = $this->uid;
        $browInfos = Db::table('zx_browser_product')->join('zx_shop shop', 'zx_browser_product.product_id = shop.id')
            ->field('zx_browser_product.id,zx_browser_product.product_id,shop.goods_name,shop.goods_introduct,shop.goods_ico,shop.member_price')
            ->where('zx_browser_product.uid', $uid)
            ->where('shop.status', 1)
            ->order('zx_browser_product.id desc')
            ->limit($start, self::$totalList)
            ->select();

        $totalCount = Db::table('zx_browser_product')->join('zx_shop shop', 'zx_browser_product.product_id = shop.id')
            ->where('zx_browser_product.uid', $uid)
            ->count();
        if ($browInfos) {
            foreach ($browInfos as &$v) {
                $v['goods_ico'] = get_cover($v['goods_ico'], 'path');
//
//                $sku = ProductSku::where('product_id', $v->id)->orderBy('member_price', 'asc')->first();
//                if ($sku) {
//                    $member_price = $sku->member_price;
//                    $parameter = $sku->value;
//                    $parameterId = $sku->id;
//                } else {
//                    $member_price = 0.00;
//                    $parameter = '无';
//                    $parameterId = 0;
//                }
//
//                $v->price = $member_price;
//                $v->parameter = $parameter;
//                $v->parameter_id = $parameterId;
            }
        }

        $this->apiSuccess('商品浏览记录', ['data' => $browInfos, 'totalCount' => $totalCount]);
    }

    /**
     * 添加商品浏览记录
     */
    public function addShopBrowser()
    {
        $id = input('id');
        $info = Db('shop')->where('status', 1)->where('id', $id)->find();
        if (!$info) {
            $this->apiError('该商品不存在');
        }

        $uid = $this->userInfo['uid'];
        $collInfo = Db('browser_product')->where('uid', $uid)->where('product_id', $id)->find();
        if ($collInfo) {
            $this->apiError('已加入浏览记录！');
        }

        $data = [
            'uid' => $uid,
            'product_id' => $id,
            'create_time' => time(),
            'update_time' => time()
        ];
        Db('browser_product')->insert($data);
        $this->apiSuccess('成功加入浏览记录！');
    }

    /**
     * 删除商品浏览记录
     */
    public function delBrowser()
    {
        $uid = $this->userinfo['uid'];
        $ids = input('ids');

        $idsArr = array_unique(explode(',', $ids));

        $res = Db('browser_product')->where('uid', $uid)->where('id', 'in', $idsArr)->delete();
        if ($res) {
            $this->apiSuccess('删除成功');
        } else {
            $this->apiError('删除失败');
        }

    }

    /**
     * 加入购物车
     */
    public function addCart()
    {
        $id = input('id');
//        $parameterId = $request->parameter_id;
//        if ($parameterId <= 0) {
//            $this->apiError('必须选择商品规格！']);
//        }
//        $id = ProductSku::where('id', $parameterId)->value('product_id');
        $info = Db('shop')->where('status', 1)->find($id);
        if (!$info) {
            $this->apiError('该商品不存在！');
        }

        $number = input('number', 1);
        if ($info['goods_num'] < $number) {
            $this->apiError('商品余量不足！');
        }

        $uid = $this->uid;
        $cartInfo = Db('product_cart')->where('uid', $uid)->where('product_id', $id)->find();
        if ($cartInfo) {
            $this->apiError('该商品已加入购物车！');
        }

        $data = [
            'uid' => $uid,
            'product_id' => $id,
            'create_time' => time(),
            'update_time' => time(),
            'number' => $number
        ];

        $res = Db('product_cart')->insert($data);
        if ($res) {
            $this->apiSuccess('成功加入购物车！');
        } else {
            $this->apiError('加入购物车失败！');
        }
    }

    /**
     * 我的购物车
     * @param
     * @return \Illuminate\Http\JsonResponse
     */
    public function cartList()
    {
        $uid = $this->uid;
        $userrank = Member::where('uid', $uid)->value('userrank');
        $data = [];
        if ($userrank <= 0) {
            $carts1 = \app\common\model\Shop::where('category_id', 1)->where('status', 1)->order('id desc')->select();
            $carts2 = \app\common\model\Shop::where('category_id', 2)->where('status', 1)->order('id desc')->select();
            $cateInfo1 = Db('shop_category')->where('id', 1)->find();
            $cateInfo2 = Db('shop_category')->where('id', 2)->find();
            $cateInfo1['icon'] = get_cover($cateInfo1['icon'], 'path');
            $cateInfo2['icon'] = get_cover($cateInfo2['icon'], 'path');
            $price1 = $this->getShopsData(0, 2);
            $price2 = $this->getShopsData(0, 34);
            $data = [
                ['type' => 1, 'title' => '初级区', 'total' => count($carts1), 'lists' => $carts1, 'cateInfo' => $cateInfo1, 'price' => $price1],
                ['type' => 2, 'title' => '高级区', 'total' => count($carts2), 'lists' => $carts2, 'cateInfo' => $cateInfo2, 'price' => $price2]
            ];

            $titleArr = [['name' => '初级区'], ['name' => '高级区']];
            $cateId = 1;
        } elseif ($userrank == 1) {
            $carts1 = \app\common\model\Shop::where('category_id', 2)->where('status', 1)->order('id desc')->select();
            $carts2 = \app\common\model\Shop::where('category_id', 3)->where('status', 1)->order('id desc')->select();
            $cateInfo1 = Db('shop_category')->where('id', 2)->find();
            $cateInfo2 = Db('shop_category')->where('id', 3)->find();
            $cateInfo1['icon'] = get_cover($cateInfo1['icon'], 'path');
            $cateInfo2['icon'] = get_cover($cateInfo2['icon'], 'path');
            $price1 = $this->getShopsData(1, 34);
            $price2 = $this->getShopsData(2, 2);

            $data = [
                ['type' => 2, 'title' => '高级区', 'total' => count($carts1), 'lists' => $carts1, 'cateInfo' => $cateInfo1, 'price' => $price1],
                ['type' => 3, 'title' => '复消区', 'total' => count($carts2), 'lists' => $carts2, 'cateInfo' => $cateInfo2, 'price' => $price2]
            ];
            $titleArr = [['name' => '高级区'], ['name' => '复消区']];
            $cateId = 2;
        } else {
            $carts = \app\common\model\Shop::where('category_id', 3)->where('status', 1)->order('id desc')->select();
            $cateInfo = Db('shop_category')->where('id', 3)->find();
            $cateInfo['icon'] = get_cover($cateInfo['icon'], 'path');
            $price = $this->getShopsData(1, 2);
            $data = [
                ['type' => 3, 'title' => '复消区', 'total' => count($carts), 'lists' => $carts, 'cateInfo' => $cateInfo, 'price' => $price]
            ];

            $titleArr = [['name' => '复消区']];
            $cateId = 3;
        }
        foreach ($data as $val) {
            if ($val) {
                foreach ($val['lists'] as $v) {
                    $v->goods_ico = get_cover($v->goods_ico, 'path');
                    $v->number = 1;
                    $v->checked = false;
                }
            }
        }

        $this->apiSuccess('购物车清单', ['data' => $data, 'titles' => $titleArr, 'cateId' => $cateId]);
    }

    /**
     * 删除购物车商品
     */
    public function clearCart()
    {
        $idsStr = input('ids');
        if (!$idsStr) {
            $this->apiError('参数缺失');
        }
        $idsArr = json_decode($idsStr, true);
        $uid = $this->uid;
        $res = Db('product_cart')->where('uid', $uid)->whereIn('id', $idsArr)->delete();
        if ($res) {
            $this->apiSuccess('删除成功');
        } else {
            $this->apiError('删除失败');
        }
    }
}